package me.security.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import me.security.bean.Role;

@Repository
public class RoleDao extends BaseDaoImpl <Role> {
	
	public JdbcTemplate jbct;
	
	private final Logger logger = Logger.getLogger("RoleDao");
	public List<Role> findAll() {
		String sql = "select * from role_info";
		logger.info("[" +jbct +"]");
		List listRole = jbct.queryForList(sql);
		return listRole;
	}

	public int add(Role t) {
	  int a = jbct.update("insert into role_info(roleid,rolename,inputTime,inputUser)values(?,?,?,?)", 
			   new Object[]{t.getRoleId(),t.getRoleName(),t.getInputTime(),t.getInputUser()});
	   return a;
	}

	public boolean delete(String id) {
		int a = jbct.update("delete from role_info where roleid = '"+id+"'");
		return a == 0;
	}

	public int update(final Role t, final String id) {
		int a = jbct.update("update role_info set roleid = ? , rolename = ? where roleid = ?", 
							new PreparedStatementSetter(){  
					            public void setValues(PreparedStatement ps) throws SQLException{  
					                ps.setString(1, t.getRoleId());  
					                ps.setString(2, t.getRoleName());  
					                ps.setString(3, id);  
					            }
					        }
		);
		return a;
	}

	public Role findById(String id) {
		   final Role r  = new Role();  
	       jbct.query("select * from role_info where roleid = ?",   
	                 new Object[] { id },   
	                 new RowCallbackHandler() {     
	                    public void processRow(ResultSet rs) throws SQLException {     
				            r.setRoleId(rs.getString("roleid"));  
				            r.setRoleName(rs.getString("rolename"));  
				            r.setInputTime(rs.getString("inputTime"));
				            r.setInputUser(rs.getString("inputUser"));   
				        }     
	                 }
	        );   
	        return r; 
	}

	public int count() {
		return jbct.update("select count(*) from role_info");
	}

	public JdbcTemplate getJbct() {
		return jbct;
	}

	public void setJbct(JdbcTemplate jbct) {
		this.jbct = jbct;
	}
	

}
